# -*- coding: utf-8 -*-
'''
Created on 2011-3-12
根据用户的城市信息和好友列表到活动表里查找用户的同城以及异地好友的活动信息，并到用户表里把没有加入进来的朋友邀请进来
@author: Tony
'''
from models import Activity
from goplay.sinaweibo.models import UserInfo
from goplay.sinaweibo.models import Province

def getFriendActivity(city,friends):
    friends_list=friends.rsplit(',')
    friends_name_list=friends_list[0:len(friends_list):2]
    friends_image_list=friends_list[1:len(friends_list):2]
    fr_noactivity=[]#没有发布活动的好友
    fr_city_activity=[]#好友的同城活动
    fr_nocity_activity=[]#好友的非同城活动 
    #recommened_activity=[] 
    userinfo={}    #没有活动记录的好友信息
    img={}
    a_id=0
    #好友的活动                 
    for friend in friends_name_list:
        
        #用datetime排序，当一个好友有多个活动是，只显示最新的一个活动
        activity=Activity.objects.filter(username=friend).order_by('-datetime').values('id','username','province','city','activityname','address','member','date','datetime')
        if activity:
            cityName=Province.objects.filter(province_id=activity[0].get('province'),city_id=activity[0].get('city'))
            #print cityName[0]
            '''if (activity[0].get('city')==city):
                image=UserInfo.objects.filter(username=friend).values('id','profile_image')
                img=image[0]
                img.update(userid=img.pop('id'))#更改键值id为userid,防止与活动的id重名冲突
                activity[0]['city']=cityName[0]
                fr_city_activity.append(dict(activity[0],**img))
                
            else:
                image=UserInfo.objects.filter(username=friend).values('id','profile_image')
                img=image[0]
                img.update(userid=img.pop('id'))
                activity[0]['city']=cityName[0]
                fr_nocity_activity.append(dict(activity[0],**img))'''
            activity[0]['a_id']=a_id
            image=UserInfo.objects.filter(username=friend).values('id','profile_image')
            img=image[0]
            img.update(userid=img.pop('id'))#更改键值id为userid,防止与活动的id重名冲突
            activity[0]['cityname']=cityName[0]
            fr_city_activity.append(dict(activity[0],**img))  
            a_id=a_id+1      
        else:
            i=friends_name_list.index(friend)
            image=friends_image_list[i]
            userinfo['friend']=friend
            userinfo['profile_image']=image              
            fr_noactivity.append(dict(userinfo))            
    #非好友的活动，系统自动推荐
    '''activity=Activity.objects.filter(city=city,is_open=0).values('username','activityname','date','datetime')
    print len(activity)
    recommened_activity=activity
    print recommened_activity'''
    return fr_city_activity,fr_nocity_activity,fr_noactivity
    